package controller

import (
	"common-admin/e"
	"common-admin/entity"
	"common-admin/model"
	"common-admin/util"
	"github.com/gin-gonic/gin"
	"net/http"
)

var adminModel model.Admin

type user struct {
	Name   string `json:"name"`
	Avatar string `json:"avatar"`
}

type LoginData struct {
	Token string `json:"token"`
	User  user   `json:"user"`
}

func Login(c *gin.Context) {
	mobile := c.PostForm("mobile")
	password := c.PostForm("password")
	captchaId := c.PostForm("captcha_id")
	captcha := c.PostForm("captcha")
	//fmt.Printf("%s, %s, %s, %s", mobile, password, captchaId, captcha)
	res := util.VerifyCaptcha(captchaId, captcha)
	if !res {
		c.JSON(http.StatusOK, util.ReturnData(e.ERROR_VERIFY_CAPTCHA, e.GetMsg(e.ERROR_VERIFY_CAPTCHA)))
		return
	}

	//admin := adminModel.FindByUsername(mobile)

	var admin entity.Admin
	admin.Username = mobile
	adminModel.FindOne(&admin)
	if len(admin.Password) < 1 || admin.Password != util.Md5(password) {
		c.JSON(http.StatusOK, util.ReturnData(e.ERROR_LOGIN, e.GetMsg(e.ERROR_LOGIN)))
		return
	}
	token, err := util.CreatToken(admin.Id)
	if err != nil {
		c.JSON(http.StatusOK, util.ReturnData(e.ERROR_CREATE_CAPTCHA, e.GetMsg(e.ERROR_CREATE_CAPTCHA)))
		return
	}
	c.Header("authorization", "Bearer "+token)
	//fmt.Println("token:" + token)

	var loginData LoginData
	loginData.Token = token
	loginData.User = user{admin.Name, admin.Avatar}
	//uid, err := util.ParseToken(token)
	//fmt.Println(uid)
	c.JSON(http.StatusOK, util.ReturnData(e.SUCCESS, "登录成功", loginData))
}
